<?php

namespace app\api\controller;

use app\facade\Redis;
use rsa\Rsa;
use app\models\{
    User as Users,
    Moneylog,
    Shopinfo,
    Project,
    MerchantItem,
    Config
};
use think\Facade\Config as Configs;
use app\facade\Mns;
use app\facade\Yun;
use app\facade\Eth;
use think\Validate;
use think\Db;

class User extends Base
{
    //注册账号

    public function register()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'code' => 'require',
            'password' => 'require',
        ], [
            'mobile.require' => '手机号码不能为空',
            'code.require' => '验证码不能为空',
            'password.require' => '登录密码不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        //识别验证码是否正确
        if (!(new Mns())->checkCode($data['code'], $data['mobile'])) {
            $this->result([], 1, '手机验证码错误');
        }
        $pid = 0;
        if (!empty($data['invit'])) {
            //判断邀请码是否存在
            $code = (new Users())->where('code', $data['invit'])->find();
            if (empty($code)) {
                $this->result([], 1, '邀请码错误');
            }
            $pid = $code['id'];
        }
        //判断手机号码是否已存在
        $user = (new Users())->where('mobile', $data['mobile'])->find();
        if (!empty($user)) {
            $this->result([], 1, '手机号码已注册');
        }
        $mycode = recode(new Users());
        Db::startTrans();
        try {
            (new Users())->insert([
                'mobile' => $data['mobile'],
                'password' => md5(md5($data['password'])),
                'code' => $mycode,
                'pid' => $pid,
                'created' => date('Y-m-d H:i:s')
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result($e->getMessage(), 1, '注册失败，请重试');
        }
        $this->result([], 0, '注册成功');
    }

    //账号登录

    public function Login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ], [
            'mobile.require' => '手机号码不能为空',
            'password.require' => '密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Users())
            ->where(['mobile' => $data['mobile'], 'password' => md5(md5($data['password']))])
            ->find();
        if ($user) {
            $token = md5(md5($user['id'] . $user['code'] . time()));
            (new Users())->where('id', $user['id'])->update(['token' => $token]);
            Redis::setex($token, 86400 * 5, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        }
        $this->result([], 1, '账号不存在或密码错误');
    }

    //忘记密码

    public function Forget()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'code' => 'require',
            'password' => 'require',
        ], [
            'mobile.require' => '登录账号不能为空',
            'code.require' => '验证码不能为空',
            'password.require' => '密码不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        //识别验证码是否正确
        if (!(new Mns())->checkCode($data['code'], $data['mobile'])) {
            $this->result([], 1, '验证码错误');
        }
        //账号不存在
        $user = (new Users())->where('mobile', $data['mobile'])->find();
        if (empty($user)) {
            $this->result([], 1, '账号不存在');
        }
        $password = md5(md5($data['password']));
        if ($user['password'] == $password) {
            $this->result([], 1, '修改密码不能与原密码一致');
        }
        $res = (new Users())->where('id', $user['id'])->update(['password' => $password]);
        if ($res) {
            $this->result([], 0, '修改成功');
        }
        $this->result([], 1, '修改失败，请重试');
    }

    public function Info()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $ser = ["nickname", "sex", "signature", "label", "wechat", "logo"];

            foreach ($data as $name => $datas) {
                if (!in_array($name, $ser)) {
                    $this->result([], 1, '上传字段不符合系统设置');
                }
                if (!empty($datas) && $name = 'sex' && ($datas != 1 && $datas != 0 && $datas != 2)) {
                    $this->result([], 1, '性别上传值不正确');
                }
                if ($name = 'label') {
                    $datas = json_encode(json_decode($datas, true));
                }
            }
            $res = (new Users())->allowfield(true)->save($data, ['id' => $this->request->user_id]);
            if ($res) {
                $this->result([], 0, '修改成功');
            }
            $this->result([], 1, '修改失败，请重试');
        } else {
            $user = $this->request->user;
            $user['label'] = json_decode($user['label'], true);
            $this->result($user, 0, '获取成功');
        }
    }

    public function shopInfo()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'images' => 'require',
                'title' => 'require',
                'lat' => 'require',
                'lon' => 'require',
                'time' => 'require'
            ], [
                'images.require' => '店铺信息图片不能为空',
                'title.require' => '店铺名称不能为空',
                'lat.require' => '店铺经度不能为空',
                'lon.require' => '店铺纬度不能为空',
                'time.require' => '店铺营业时间段不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $images = json_decode($data['images'], true);
            $time = json_decode($data['time'], true);
            if (count($images) < 1) {
                $this->result([], 1, '店铺图片信息必须上传');
            }
            if (count($time) != 2) {
                $this->result([], 1, '店铺营业时间必须选择正确');
            }
            //判断店铺名称是否存在
            $haveshop = (new Shopinfo())->where('title', $data['title'])->find();
            if (!empty($haveshop) && $haveshop['userid'] != $this->request->user_id) {
                $this->result([], 1, '店铺名称已存在');
            }
            $shopinfo = (new Shopinfo())->where('userid', $this->request->user_id)->find();
            $data['userid'] = $this->request->user_id;
            if (!empty($shopinfo)) {
                if ($shopinfo['status'] != 2) {
                    $data['status'] = 1;
                }
                $res = (new Shopinfo())->allowfield(true)->save($data, ['id' => $shopinfo['id']]);
            } else {
                $res = (new Shopinfo())->allowfield(true)->save($data);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            $shopinfo = (new Shopinfo())->where('userid', $this->request->user_id)->find();
            $shopinfo['images'] = json_decode($shopinfo['images'], true);
            $shopinfo['time'] = json_decode($shopinfo['time'], true);
            $this->result($shopinfo, 0, '获取成功');
        }
    }

    public function merchant_item()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'images' => 'require',
                'title' => 'require',
                'info' => 'require',
                'project' => 'require',
                'time' => 'require'
            ], [
                'images.require' => '项目信息图片不能为空',
                'title.require' => '项目名称不能为空',
                'info.require' => '项目介绍不能为空',
                'project.require' => '项目类型不能为空',
                'time.require' => '项目可预约时间段不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $images = json_decode($data['images'], true);
            $time = json_decode($data['time'], true);
            if (count($images) < 1) {
                $this->result([], 1, '图片信息必须上传');
            }
            $shopinfo = (new Shopinfo())->where('userid', $this->request->user_id)->find();
            if (empty($shopinfo) || $shopinfo['status'] != 2) {
                $this->result([], 1, '您还不是商家');
            }
            $data['uid'] = $shopinfo['userid'];
            $data['shopid'] = $shopinfo['id'];
            if (!empty($data['id'])) {
                $res = (new MerchantItem())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new MerchantItem())->allowfield(true)->save($data);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            $id = $this->request->get('id/d', 0);
            $shopinfo = (new MerchantItem())->where('id', $id)->find();
            if ($shopinfo) {
                $shopinfo['project_text'] = (new Project())->where('id', $shopinfo['project'])->value('name');
                $shopinfo['images'] = json_decode($shopinfo['images'], true);
            }

            $this->result($shopinfo, 0, '获取成功');
        }
    }

    public function mymerchant()
    {
        $list = (new MerchantItem())->field('status,title,price')->where('uid', $this->request->user_id)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['num'] = 0;
        }
        $this->result($list, 0, '获取成功');
    }

    public function getmerchant()
    {
        $id = $this->request->post('id/d', 0);
        $shopinfo = (new MerchantItem())->where(['id' => $id, 'uid' => $this->request->user_id])->find();
        if (!$shopinfo) {
            $this->result([], 1, '操作失败，项目不存在');
        }
        $status = 1;
        if ($shopinfo['status'] == 1) {
            $status = 2;
        }
        $res = (new MerchantItem())->where(['id' => $id])->update(['status' => $status]);
        if ($res) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败，请重试');
    }

    public function project()
    {
        $list = (new Project())->select();
        $this->result($list, 0, '获取成功');
    }
}
